// pages/nav/index.js
import { authRequest, parserDate, minutes } from '../../utils/net';
Page({
  data: {
    height: 0,
    lat: 0,
    log: 0,
    predict: 1.0,
    start: '',
    minutes: 0,
    bike_id: 0
  },
  onLoad: function () {
    var that = this;
    // 使用 wx.createMapContext 获取 map 上下文 
    that.mapCtx = wx.createMapContext('map');
    // 获取开始使用的事件
    authRequest({
      url: '/current_rider',
      method: 'GET',
      success: function (res) {
        console.log(res.data.data[0]);
        that.setData({
          start: res.data.data[0].start_at,
          bike_id: res.data.data[0].bike_id
        });
      }
    });

    // 加载动画
    wx.showLoading({
      title: '加载中',
    });
    // 1.5s后关闭加载动画
    setTimeout(function () {
      wx.hideLoading()
    }, 1500);

    that.setData({
      predict: that.data.predict.toFixed(1)
    });


    // 页面初始化 options为页面跳转所带来的参数
    wx.getLocation({
      type: 'gcj02', //默认为 wgs84 返回 gps 坐标，gcj02 返回可用于wx.openLocation的坐标
      // 返回可以用于wx.openLocation的经纬度
      success: function (res) {
        var lat = res.latitude;
        var log = res.longitude;
        that.setData({
          lat: lat,
          log: log
        })
      },
    });
    setInterval(function () {
      var end = new Date();
      var start = that.data.start;
      that.setData({
        minutes: minutes(parserDate(start), end),
        // parseInt返回整数部分
        predict: (parseInt(minutes(parserDate(start), end) / 30) - 0 + 1).toFixed(1)
      });
    }, 1000);
    wx.getSystemInfo({
      success: function (res) {
        console.log(res);
        // 获取手机基本信息使用窗口宽高
        var width = res.windowWidth;
        var height = res.windowHeight;
        console.log(height)
        that.setData({
          height: height - 140,
          controls: [{
            id: 1,
            iconPath: '/images/img1.png',
            position: {
              left: 20,
              top: height - 200,
              width: 40,
              height: 40
            },
            clickable: true
          }]
        })
      }
    });
  },
  controltap(e) {
    var that = this
    console.log(e.controlId)
    if (e.controlId == 1) {
      // 将地图中心移动到当前定位点，需要配合map组件的show-location使用
      that.mapCtx.moveToLocation();
    }
  },
  uplatch: function () {
    wx.reLaunch({
      url: '/pages/index/index'
    })
  },
  onUnload: function () {
    var that = this
    // 页面关闭跳转到结算页面
    wx.navigateTo({
      url: '../clearing/index',
    })
    wx.setStorageSync('minutes', that.data.predict);
  }

})